package com.hyts.apidoc.swagger.factory.adoc;

import com.hyts.apidoc.swagger.config.SwaggerConfig;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.SafeMode;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.apidoc.swagger.factory
 * author:Libo/Alex
 * create-date:2019-05-12 08:09
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: AsciidoctorFactory 用于创建Ascildoctor对象
 */
public class AsciidoctorFactory {


    final Map<String,Object> DEFAULT_ATTRBUTE;

    OptionsBuilder optionsBuilder;

    Asciidoctor asciidoctor;

    /**
     * 初始化左侧菜单
     */
    {
        DEFAULT_ATTRBUTE = new HashMap<>();
        DEFAULT_ATTRBUTE.put("doctype", "book");
        DEFAULT_ATTRBUTE.put("toc", "left");//左侧
        DEFAULT_ATTRBUTE.put("toclevels", "3");//三级菜单
    }

    /**
     * 根据书写生成对应的html文档
     * @param attributes
     * @return
     */
    public AsciidoctorFactory create(Map<String,Object> attributes){
        //JRubyAsciidoctor.create();
        asciidoctor = Asciidoctor.Factory.create();
        if(attributes == null || attributes.isEmpty()){
            attributes = DEFAULT_ATTRBUTE;
        }
        optionsBuilder = OptionsBuilder.options().docType("book").safe(SafeMode.SAFE).mkDirs(true)
                .backend("html5").headerFooter(true).attributes(attributes);
        return this;
    }

    /**
     * 采用默认操作生成对应的文档html文件
     * @return
     */
    public AsciidoctorFactory create(){
        create(null);
        return this;
    }

    /**
     * 根据文件路径转换操作
     * @param inputFilePath 输入文件路径
     * @param outputFilePath 输出文件路径
     * @return  AsciidoctorFactory 返回对象工程奔雷
     */
    public AsciidoctorFactory convertHtmlFromAscii(String inputFilePath,String outputFilePath){
        optionsBuilder.toFile(Paths.get(outputFilePath).toFile());
        asciidoctor.convertFile(Paths.get(inputFilePath).toFile(),optionsBuilder);
        return this;
    }

    /**
     * 根据文件路径转换操作
     * @param outputFilePath 输出文件路径
     * @return
     */
    public AsciidoctorFactory convertHtmlFromAscii(String outputFilePath){
        optionsBuilder.toFile(Paths.get(outputFilePath).toFile());
        asciidoctor.convertFile(Paths.get(SwaggerConfig.OUTPUT_FILE_PATH+".adoc").toFile(),optionsBuilder);
        return this;
    }

    /**
     * 创建实例对象
     * @return
     */
    public static AsciidoctorFactory newInstance(){
        return new AsciidoctorFactory();
    }

}
